package main

import (
	"bufio"
	"flag"
	"log"
	"net"
	"strconv"
	"sync"
)

var host = flag.String("host", "127.0.0.1", "host")
var port = flag.String("port", "3333", "port")

func main() {
	flag.Parse()

	client, err := net.Dial("tcp", *host+":"+*port)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	var wg sync.WaitGroup
	wg.Add(2)

	go ReciveMsg(client, &wg)
	go SendSmg(client, &wg)

	wg.Wait()
}

func SendSmg(conn net.Conn, wg *sync.WaitGroup) {
	defer wg.Done()
	reader := bufio.NewReader(conn)
	for i := 1; i <= 10; i++ {
		line, err := reader.ReadString(byte('\n'))
		if err != nil {
			log.Print("Error to read message because of ", err)
			return
		}
		log.Println("read", line)
	}
}

func ReciveMsg(conn net.Conn, wg *sync.WaitGroup) {
	defer wg.Done()
	for i := 10; i > 0; i-- {
		_, err := conn.Write([]byte("hello" + strconv.Itoa(i) + "\r\n"))

		if err != nil {
			log.Println("Error to send message because of ", err.Error())
			break
		}
	}
}
